package mt.omid.dimomuth.mgm;


import static java.util.logging.Level.*;
import static mt.omid.dimomuth.internal.ErrorList.*;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;


public class ManagementIf implements Runnable
{

    protected int      port;
    protected Logger   logger;

    private MgmHandler handler;
    private Thread     lsnrThrd;


    public ManagementIf( int port, Logger lgr )
    {
	this.port = port;
	this.logger = lgr;
    }

    public void start( MgmHandler hndl )
    {
	this.handler = hndl;
	lsnrThrd = new Thread( this, "MgmListener" );
	lsnrThrd.start();
    }

    public void run()
    {
	try
	{
	    startListening();
	}
	catch( MgmServerException e )
	{
	    logger.log( WARNING, "Exception in MgmServer listening.", e );
	}
    }

    /**
     * Module instance(implementation) have to start MgmServer it-self by
     * passing a handler interface like itself to it.
     * 
     * @param hndl
     * @return
     * @throws MgmServerException
     */
    private int startListening() throws MgmServerException
    {

	if( handler == null )
	{
	    logger.warning( "Error-" + MGM_NULL_HANDLER
		    + "-MgmHandler of module instance is null, so shutting down Mgm submodule." );
	    return MGM_NULL_HANDLER;
	}

	try
	{
	    ServerSocket srvSock = new ServerSocket( port );

	    int i = 0;
	    while( true )
	    {
		i++;
		Socket sock = srvSock.accept();
		Thread thread = new Thread( new MgmProtocol( sock, logger, this.handler ),
			"MgmServerThread-" + i );
		thread.start();
		logger.info( "New client connected[" + sock.getInetAddress() + ":" + sock.getPort()
			+ "]" + thread.getName() );
	    }
	}
	catch( IOException e )
	{
	    logger.log( INFO, "Error-" + MGM_SERVER_START_EXCP
		    + ":IOException in starting serve thread.", e );
	    throw new MgmServerException( "Error-" + MGM_SERVER_START_EXCP
		    + ":IOException in starting serve thread.", e );
	}
    }

    public void shutdown()
    {
	lsnrThrd.stop();
    }
}
